<template>
  <LoginBox>
    <div class="login">
      <div class="logo">
        <img src="@/assets/logo1.png" />

        <div class="qr-code-container">
          <img v-lazy="qrcodeEntity.imgData" />
        </div>
        <div style="text-align: center; margin-top: 5px">
          <span class="email-code-login-btn" @click="toEmailLogin"
            >邮箱登录</span
          >
        </div>
      </div>
    </div>
  </LoginBox>

  <teleport to=".qr-code-container">
    <div
      class="wraning-msg-box"
      v-if="qrcodeEntity.state == 1"
      @click="reloadQrCode"
    >
      <span class="msg">
        二维码已过期
        <p>点击重新生成</p>
      </span>
    </div>

    <div class="success-msg-box" v-if="qrcodeEntity.state == 2">
      <span class="msg">
        用户已扫描
        <p>待用户确认</p>
      </span>
    </div>

    <div
      class="error-msg-box"
      v-if="qrcodeEntity.state == 3"
      @click="reloadQrCode"
    >
      <span class="msg">
        用户取消扫码登录
        <p>点击重新生成</p>
      </span>
    </div>
  </teleport>
</template>

<script lang='ts'>
import {
  defineComponent,
  onUnmounted,
  onMounted,
  onBeforeMount,
  reactive,
} from "vue";

import { useRouter } from "vue-router";

import LoginBox from "@/components/LoginBox.vue";

import { useQrCodeAPI } from "@/server";

import { AutheUtils } from "@/utils";

export default defineComponent({
  name: "qr-login",
  components: {
    LoginBox,
  },
  setup(props) {
    const qrcodeAPI = useQrCodeAPI();
    const router = useRouter();

    const toEmailLogin = () => router.push({ name: "login" });
    const toIndex = () => router.push({ name: "index" });

    /*
        二维码状态信息
        state: 0标识正常 1标识过期 2标识被扫描 3标识用户取消登录 4完成扫码，去后端获取token
      */
    const qrcodeEntity = reactive({
      state: 0,
      imgData: "",
      channelId: "",
    });

    const intervalArray: Array<number> = [];

    const clearAllInterval = ()=>{
        for(let item of intervalArray){
          try{
            clearInterval(item)
          }catch(err){}
        }
    }

    let close: (() => void) | undefined;
    const startListener = () => {
      if (close) {
        close();
        close = undefined;
      }
      const self = setInterval(async () => {
        close = () => {
            clearInterval(self);
            let index:number|any
             for(let i = 0;i<intervalArray.length;i++){
                if(intervalArray[i] === self){
                  index=i;
                  break;
                }
              }
              intervalArray.splice(index,1);

          }
        try {
          const { data } = await qrcodeAPI.validCodeStatus(
            qrcodeEntity.channelId
          );

          if (data.code == 200) {
            qrcodeEntity.state = data.status;
            console.log(data);

            if (data.status == 4 || data.status == 1 || data.status == 3) {
              close();
            }

            if (data.status == 4) {
              AutheUtils.setToken(data.token);
              toIndex();
            }
          }
        } catch (error) {
          console.error(error);
          close();
        }
      }, 3000);

      intervalArray.push(self);
    };

    onUnmounted(() => {
      clearAllInterval();
    });

    // 加载二维码
    const reloadQrCode = async () => {
      try {
        const { data } = await qrcodeAPI.getQrCode();

        if (data.code == 200) {
          qrcodeEntity.imgData = "data:image/png;base64," + data.data;
          qrcodeEntity.channelId = data.channelId;
          qrcodeEntity.state = 0;

          startListener();
        }
      } catch (e) {
        console.error(e);
      }
    };

    onBeforeMount(() => {
      // 初始调用
      reloadQrCode();
    });

    return {
      toEmailLogin,
      qrcodeEntity,
      reloadQrCode,
    };
  },
});
</script>

<style lang='less' scoped>
.login {
  user-select: none;
  text-align: center;
  padding: 15px;
  position: relative;
  height: 100%;
  .logo {
    padding-top: 60px;
    img {
      width: 200px;
    }
  }

  .qr-code-container {
    width: 100%;
    height: 300px;
    padding: 40px;
    position: relative;
    img {
      height: 220px;
      width: 220px;
      border: 15px solid rgb(5, 5, 5);
    }

    .extra-pub {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      top: 0;
      background-color: rgba(0, 0, 0, 0.8);
      text-align: center;
    }

    .success-msg-box {
      .extra-pub();
      .msg {
        color: greenyellow;
        font-size: 18px;
        text-shadow: 0 0 2px rgb(0, 166, 243);
        position: relative;
        top: 50%;
        display: inline-block;
        transform: translateY(-50%);
        p {
          padding-top: 15px;
          color: #fff;
          font-size: 13px;
        }
      }
    }
    .error-msg-box {
      .extra-pub();
      cursor: pointer;
      .msg {
        color: rgb(209, 12, 94);
        font-size: 18px;
        text-shadow: 0 0 1px rgb(251, 255, 12);
        position: relative;
        top: 50%;
        display: inline-block;
        transform: translateY(-50%);
        p {
          padding-top: 15px;
          color: #fff;
          font-size: 13px;
        }
      }
    }
    .wraning-msg-box {
      .extra-pub();
      cursor: pointer;
      .msg {
        color: salmon;
        font-size: 18px;
        text-shadow: 0 0 1px red;
        position: relative;
        top: 50%;
        display: inline-block;
        transform: translateY(-50%);
        p {
          padding-top: 15px;
          color: #fff;
          font-size: 13px;
        }
      }
    }
  }
  .email-code-login-btn {
    color: #313131bd;
    cursor: pointer;
    &:hover {
      color: #fff;
    }
  }
}
</style>